<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>3D Physics Picking — Alien.js</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto+Mono">
    <link rel="stylesheet" href="../assets/css/style.css">

    <script type="module">
        import { BasicShadowMap, BloomCompositeMaterial, BoxGeometry, BufferLoader, Color, ColorManagement, DirectionalLight, EnvironmentTextureLoader, EventEmitter, Group, HemisphereLight, IcosahedronGeometry, ImageBitmapLoaderThread, LinearSRGBColorSpace, LuminosityMaterial, MathUtils, Mesh, MeshBasicMaterial, MeshPhongMaterial, MeshStandardMaterial, OimoPhysicsBuffer, OimoPhysicsController, OrthographicCamera, PanelItem, PerspectiveCamera, PlaneGeometry, PointLight, Raycaster, Reflector, RepeatWrapping, Scene, SceneCompositeDistortionMaterial, ShaderChunk, ShadowMaterial, Sound3D, SphereGeometry, TextureLoader, Thread, UI, UnrealBloomBlurMaterial, Vector2, Vector3, WebAudio, WebGLRenderTarget, WebGLRenderer, delayedCall, getFullscreenTriangle, getKeyByValue, ticker } from '../../build/alien.three.js';

        const isDebug = /[?&]debug/.test(location.search);

        const colors = {
            lightColor: 0xf44336
        };

        const layers = {
            default: 0,
            picking: 1
        };

        class ScenePhysics extends EventEmitter {
            constructor(shapes) {
                super();

                this.shapes = shapes;

                this.force = new Vector3();
                this.contact = null;

                this.initPhysics();

                this.addListeners();
            }

            initPhysics() {
                this.physics = new OimoPhysicsBuffer();

                this.shapes.forEach(shape => this.physics.add(shape));

                this.physics.add({
                    name: 'mouse',
                    kinematic: true
                });
            }

            addListeners() {
                this.physics.setContactCallback('cube', this.onContact);
            }

            // Event handlers

            onContact = (body/* , name, contact */) => {
                if (this.contact) {
                    return;
                }

                const linearVelocity = body.getLinearVelocity();
                const mass = body.getMass();

                this.force.addScaledVector(linearVelocity, mass);
                this.force.multiplyScalar(0.4);

                const force = this.force.length();

                if (force > 0.3) {
                    this.contact = true;

                    this.emit('contact', { force });

                    delayedCall(250, () => {
                        this.contact = false;
                    });
                } else {
                    this.force.multiplyScalar(0);
                }
            };

            // Public methods

            step = () => {
                this.physics.step();

                this.emit('buffer', { array: this.physics.array, buffer: [this.physics.array.buffer] });
            };

            update = array => {
                this.physics.array = array;

                this.step();
            };

            add = object => {
                this.physics.add(object);
            };

            remove = name => {
                this.physics.remove(name);
            };

            setGravity = gravity => {
                this.physics.setGravity(gravity);
            };

            setPosition = (name, position) => {
                this.physics.setPosition(name, position);
            };

            setOrientation = (name, orientation) => {
                this.physics.setOrientation(name, orientation);
            };

            setLinearVelocity = (name, linearVelocity) => {
                this.physics.setLinearVelocity(name, linearVelocity);
            };

            setAngularVelocity = (name, angularVelocity) => {
                this.physics.setAngularVelocity(name, angularVelocity);
            };
        }

        class ScenePhysicsThread {
            constructor() {
                this.startTime = performance.now();

                this.addListeners();
            }

            addListeners() {
                addEventListener('message', this.onMessage);
            }

            // Event handlers

            onMessage = ({ data }) => {
                this[data.message.fn].call(this, data.message);
            };

            onBuffer = ({ array, buffer }) => {
                postMessage({ event: 'buffer', message: { array } }, buffer);
            };

            onContact = ({ force }) => {
                postMessage({ event: 'contact', message: { force } });
            };

            // Public methods

            init = ({ shapes }) => {
                this.physics = new ScenePhysics(shapes);
                this.physics.on('buffer', this.onBuffer);
                this.physics.on('contact', this.onContact);

                this.physics.step();

                postMessage({ event: 'ready' });
            };

            update = ({ array }) => {
                this.physics.update(array);

                ticker.onTick(performance.now() - this.startTime);
            };

            add = ({ object }) => {
                this.physics.add(object);
            };

            remove = ({ name }) => {
                this.physics.remove(name);
            };

            setGravity = ({ gravity }) => {
                this.physics.setGravity(gravity);
            };

            setPosition = ({ name, position }) => {
                this.physics.setPosition(name, position);
            };

            setOrientation = ({ name, orientation }) => {
                this.physics.setOrientation(name, orientation);
            };

            setLinearVelocity = ({ name, linearVelocity }) => {
                this.physics.setLinearVelocity(name, linearVelocity);
            };

            setAngularVelocity = ({ name, angularVelocity }) => {
                this.physics.setAngularVelocity(name, angularVelocity);
            };
        }

        class ScenePhysicsController extends OimoPhysicsController {
            constructor() {
                super();

                this.buffer = [];
            }

            init() {
                this.initEngine();

                this.addListeners();
            }

            initEngine() {
                this.thread = new Thread({
                    imports: [
                        ['../../build/alien.three.js', 'EventEmitter', 'OimoPhysicsBuffer', 'Vector3', 'delayedCall', 'ticker']
                    ],
                    classes: [ScenePhysics],
                    controller: [ScenePhysicsThread, 'void init', 'void update', 'void add', 'void remove', 'void setGravity', 'void setPosition', 'void setOrientation', 'void setLinearVelocity', 'void setAngularVelocity']
                });

                this.thread.init({ shapes: this.shapes });
            }

            addListeners() {
                this.thread.on('buffer', this.onBuffer);
                this.thread.on('contact', this.onContact);
            }

            // Event handlers

            onBuffer = ({ array }) => {
                this.buffer.push(array);
            };

            onContact = ({ force }) => {
                AudioController.trigger('gong', force);
            };

            // Public methods

            update = () => {
                const array = this.buffer.shift();

                if (array) {
                    this.step(array);

                    this.thread.update({ array, buffer: [array.buffer] });
                }
            };

            addJoint = object => {
                this.thread.add({ object });
            };

            remove = name => {
                this.thread.remove({ name });
            };

            setGravity = gravity => {
                this.thread.setGravity({ gravity });
            };

            setPosition = (name, position) => {
                this.thread.setPosition({ name, position });
            };

            setOrientation = (name, orientation) => {
                this.thread.setOrientation({ name, orientation });
            };

            setLinearVelocity = (name, linearVelocity) => {
                this.thread.setLinearVelocity({ name, linearVelocity });
            };

            setAngularVelocity = (name, angularVelocity) => {
                this.thread.setAngularVelocity({ name, angularVelocity });
            };

            ready = () => this.init();
        }

        class Ball extends Group {
            constructor() {
                super();

                this.position.z = 1;

                // Physics
                this.name = 'ball';
                this.radius = 0.075;
                this.autoSleep = false;

                this.initLight();
            }

            initLight() {
                const light = new PointLight(colors.lightColor, 0.9, 4.4, 0);
                this.add(light);
            }

            async initMesh() {
                const { physics } = WorldController;

                const geometry = new IcosahedronGeometry(this.radius, 3);

                const material = new MeshPhongMaterial({
                    color: new Color(colors.lightColor).offsetHSL(0, 0, -0.3)
                });

                // Based on https://github.com/mrdoob/three.js/blob/dev/examples/jsm/shaders/SubsurfaceScatteringShader.js by daoshengmu

                material.onBeforeCompile = shader => {
                    shader.uniforms.thicknessDistortion = { value: 0.1 };
                    shader.uniforms.thicknessAmbient = { value: 0 };
                    shader.uniforms.thicknessAttenuation = { value: 0.7 };
                    shader.uniforms.thicknessPower = { value: 1 };
                    shader.uniforms.thicknessScale = { value: 16 };

                    shader.fragmentShader = shader.fragmentShader.replace(
                        'void main() {',
                        /* glsl */ `
                        uniform float thicknessDistortion;
                        uniform float thicknessAmbient;
                        uniform float thicknessAttenuation;
                        uniform float thicknessPower;
                        uniform float thicknessScale;

                        void RE_Direct_Scattering(IncidentLight directLight, vec3 geometryPosition, vec3 geometryNormal, vec3 geometryViewDir, vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {
                            vec3 thickness = directLight.color * 0.8;
                            vec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));
                            float scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;
                            vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;
                            reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;
                        }

                        void main() {
                        `
                    );

                    shader.fragmentShader = shader.fragmentShader.replace(
                        '#include <lights_fragment_begin>',
                        ShaderChunk.lights_fragment_begin.replaceAll(
                            'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );',
                            /* glsl */ `
                            RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
                            RE_Direct_Scattering(directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);
                            `
                        )
                    );
                };

                const mesh = new Mesh(geometry, material);
                mesh.castShadow = true;
                mesh.receiveShadow = true;
                mesh.layers.enable(layers.picking);
                this.add(mesh);

                // Physics
                physics.add(mesh);
            }

            // Public methods

            ready = () => this.initMesh();
        }

        class Cube extends Group {
            constructor() {
                super();

                // Physics
                this.name = 'cube';
                this.size = new Vector3(0.5, 0.5, 0.5);
                this.autoSleep = false;
            }

            async initMesh() {
                const { physics, anisotropy, loadTexture } = WorldController;

                const geometry = new BoxGeometry(this.size.x, this.size.y, this.size.z);

                // Second set of UVs for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                geometry.attributes.uv1 = geometry.attributes.uv;

                // Textures
                const [map, normalMap, ormMap, thicknessMap] = await Promise.all([
                    // loadTexture('uv.jpg'),
                    loadTexture('pbr/pitted_metal_basecolor.jpg'),
                    loadTexture('pbr/pitted_metal_normal.jpg'),
                    // https://occlusion-roughness-metalness.glitch.me/
                    loadTexture('pbr/pitted_metal_orm.jpg'),
                    loadTexture('pbr/pitted_metal_height.jpg')
                ]);

                map.anisotropy = anisotropy;
                normalMap.anisotropy = anisotropy;
                ormMap.anisotropy = anisotropy;
                thicknessMap.anisotropy = anisotropy;

                const material = new MeshStandardMaterial({
                    color: new Color().offsetHSL(0, 0, -0.65),
                    metalness: 0.7,
                    roughness: 2,
                    map,
                    metalnessMap: ormMap,
                    roughnessMap: ormMap,
                    aoMap: ormMap,
                    aoMapIntensity: 1,
                    normalMap,
                    normalScale: new Vector2(3, 3)
                });

                // Second channel for aoMap and lightMap
                // https://threejs.org/docs/#api/en/materials/MeshStandardMaterial.aoMap
                material.aoMap.channel = 1;

                // Based on https://github.com/mrdoob/three.js/blob/dev/examples/jsm/shaders/SubsurfaceScatteringShader.js by daoshengmu
                // Based on https://gist.github.com/mattdesl/2ee82157a86962347dedb6572142df7c

                material.onBeforeCompile = shader => {
                    shader.uniforms.thicknessMap = { value: thicknessMap };
                    shader.uniforms.thicknessDistortion = { value: 0 };
                    shader.uniforms.thicknessAmbient = { value: 0 };
                    shader.uniforms.thicknessAttenuation = { value: 1 };
                    shader.uniforms.thicknessPower = { value: 20 };
                    shader.uniforms.thicknessScale = { value: 16 };

                    shader.fragmentShader = shader.fragmentShader.replace(
                        'void main() {',
                        /* glsl */ `
                        uniform sampler2D thicknessMap;
                        uniform float thicknessDistortion;
                        uniform float thicknessAmbient;
                        uniform float thicknessAttenuation;
                        uniform float thicknessPower;
                        uniform float thicknessScale;

                        void RE_Direct_Scattering(IncidentLight directLight, vec2 uv, vec3 geometryPosition, vec3 geometryNormal, vec3 geometryViewDir, vec3 geometryClearcoatNormal, PhysicalMaterial material, inout ReflectedLight reflectedLight) {
                            vec3 thickness = directLight.color * texture(thicknessMap, uv).r;
                            vec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));
                            float scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;
                            vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;
                            reflectedLight.directDiffuse += material.diffuseColor * directLight.color * scatteringIllu * thicknessAttenuation;
                        }

                        void main() {
                        `
                    );

                    shader.fragmentShader = shader.fragmentShader.replace(
                        '#include <lights_fragment_begin>',
                        ShaderChunk.lights_fragment_begin.replaceAll(
                            'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );',
                            /* glsl */ `
                            RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
                            RE_Direct_Scattering(directLight, vAoMapUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight);
                            `
                        )
                    );
                };

                const mesh = new Mesh(geometry, material);
                mesh.castShadow = true;
                mesh.receiveShadow = true;
                mesh.layers.enable(layers.picking);
                this.add(mesh);

                // Physics
                physics.add(mesh);
            }

            // Public methods

            ready = () => this.initMesh();
        }

        import dither from '../../src/shaders/modules/dither/dither.glsl.js';

        class Floor extends Group {
            constructor() {
                super();

                this.position.y = -3.04;

                // Physics
                this.name = 'floor';
                this.size = new Vector3(100, 5, 100);
                this.density = 0;
                this.autoSleep = false;

                this.initReflector();
            }

            initReflector() {
                const { light } = WorldController;

                this.light = light;

                this.reflector = new Reflector({ blurIterations: 6 });
            }

            async initMesh() {
                const { physics, loadTexture } = WorldController;

                const geometry = new PlaneGeometry(this.size.x, this.size.z);

                const map = await loadTexture('waterdudv.jpg');
                map.wrapS = RepeatWrapping;
                map.wrapT = RepeatWrapping;
                map.repeat.set(6, 6);

                const material = new ShadowMaterial({
                    toneMapped: false
                });

                material.onBeforeCompile = shader => {
                    map.updateMatrix();

                    shader.uniforms.map = { value: map };
                    shader.uniforms.reflectMap = { value: this.reflector.renderTarget.texture };
                    shader.uniforms.reflectMapBlur = this.reflector.renderTargetUniform;
                    shader.uniforms.uvTransform = { value: map.matrix };
                    shader.uniforms.textureMatrix = this.reflector.textureMatrixUniform;

                    shader.vertexShader = shader.vertexShader.replace(
                        'void main() {',
                        /* glsl */ `
                        uniform mat3 uvTransform;
                        uniform mat4 textureMatrix;

                        out vec2 vUv;
                        out vec4 vCoord;

                        void main() {
                        `
                    );

                    shader.vertexShader = shader.vertexShader.replace(
                        '#include <project_vertex>',
                        /* glsl */ `
                        #include <project_vertex>

                        vUv = (uvTransform * vec3(uv, 1)).xy;
                        vCoord = textureMatrix * vec4(transformed, 1.0);
                        `
                    );

                    shader.fragmentShader = shader.fragmentShader.replace(
                        'void main() {',
                        /* glsl */ `
                        uniform sampler2D map;
                        uniform sampler2D reflectMap;
                        uniform sampler2D reflectMapBlur;

                        in vec2 vUv;
                        in vec4 vCoord;

                        ${dither}

                        void main() {
                        `
                    );

                    shader.fragmentShader = shader.fragmentShader.replace(
                        'gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );',
                        /* glsl */ `
                        vec2 reflectionUv = vCoord.xy / vCoord.w;

                        vec4 dudv = texture(map, vUv);
                        vec4 color = texture(reflectMap, reflectionUv);

                        vec4 blur;

                        blur = texture(reflectMapBlur, reflectionUv + dudv.rg / 256.0);
                        color = mix(color, blur, smoothstep(1.0, 0.1, dudv.g));

                        blur = texture(reflectMapBlur, reflectionUv);
                        color = mix(color, blur, smoothstep(0.5, 1.0, dudv.r));

                        gl_FragColor = color * mix(0.6, 0.75, dudv.g);

                        gl_FragColor.rgb -= (1.0 - getShadowMask()) * 0.025;

                        gl_FragColor.rgb = dither(gl_FragColor.rgb);
                        `
                    );
                };

                const mesh = new Mesh(geometry, material);
                mesh.position.y = 2.494; // 5 / 2 - 0.006
                mesh.rotation.x = -Math.PI / 2;
                mesh.receiveShadow = true;
                mesh.add(this.reflector);

                mesh.onBeforeRender = (renderer, scene, camera) => {
                    this.visible = false;
                    this.light.position.y *= -1;
                    this.reflector.update(renderer, scene, camera);
                    this.light.position.y *= -1;
                    this.visible = true;
                };

                this.add(mesh);

                // Physics mesh
                const floor = new Mesh(new BoxGeometry(this.size.x, this.size.y, this.size.z));
                floor.geometry.setDrawRange(0, 0); // Avoid rendering geometry
                this.add(floor);

                physics.add(floor);
            }

            // Public methods

            resize = (width, height) => {
                height = 1024;

                this.reflector.setSize(width, height);
            };

            ready = () => this.initMesh();
        }

        class SceneView extends Group {
            constructor() {
                super();

                this.visible = false;

                this.initViews();
            }

            initViews() {
                this.floor = new Floor();
                this.add(this.floor);

                this.cube = new Cube();
                this.add(this.cube);

                this.ball = new Ball();
                this.add(this.ball);
            }

            // Public methods

            resize = (width, height) => {
                this.floor.resize(width, height);
            };

            ready = () => Promise.all([
                this.floor.ready(),
                this.cube.ready(),
                this.ball.ready()
            ]);
        }

        class SceneController {
            static init(physics, view) {
                this.physics = physics;
                this.view = view;

                this.enabled = true;
            }

            // Public methods

            static resize = (width, height) => {
                this.view.resize(width, height);
            };

            static update = () => {
                if (!this.enabled || !this.view.visible) {
                    return;
                }

                this.physics.update();
            };

            static animateIn = () => {
                this.view.visible = true;
            };

            static ready = async () => {
                await this.view.ready();
                await this.physics.ready();
            };
        }

        class AudioController {
            static init(scene, camera, view) {
                this.scene = scene;
                this.camera = camera;
                this.view = view;

                this.addListeners();
            }

            static addListeners() {
                document.addEventListener('visibilitychange', this.onVisibility);
                window.addEventListener('pointerdown', this.onPointerDown);
            }

            // Event handlers

            static onVisibility = () => {
                if (document.hidden) {
                    WebAudio.mute();
                } else {
                    WebAudio.unmute();
                }
            };

            static onPointerDown = () => {
                window.removeEventListener('pointerdown', this.onPointerDown);

                WebAudio.resume();
            };

            // Public methods

            static trigger = (event, force) => {
                switch (event) {
                    case 'gong': {
                        const gong = new Sound3D(this.camera, 'gong');
                        gong.position.copy(this.view.cube.position);
                        gong.quaternion.copy(this.view.cube.quaternion);
                        gong.updateMatrixWorld();

                        let mesh;

                        if (isDebug) {
                            mesh = new Mesh(
                                new SphereGeometry(0.0625),
                                new MeshPhongMaterial({ color: 0x0000ff })
                            );
                            mesh.material.depthTest = false;
                            mesh.material.depthWrite = false;
                            mesh.material.transparent = true;
                            mesh.position.copy(this.view.cube.position);
                            mesh.quaternion.copy(this.view.cube.quaternion);
                            mesh.updateMatrixWorld();
                            this.scene.add(mesh);
                        }

                        const strength = MathUtils.mapLinear(force, 0, 4, 0, 1);
                        gong.sound.gain.set(MathUtils.clamp(strength * 0.5, 0, 1));
                        gong.sound.playbackRate.set(MathUtils.clamp(0.8 + strength * 0.4, 0.8, 1.2));
                        gong.sound.play();

                        delayedCall(6000, () => {
                            gong.destroy();

                            if (mesh) {
                                this.scene.remove(mesh);
                                mesh.material.dispose();
                                mesh.geometry.dispose();
                                mesh = null;
                            }
                        });
                        break;
                    }
                }
            };
        }

        class PanelController {
            static init(physics, ui) {
                this.physics = physics;
                this.ui = ui;

                this.initPanel();
            }

            static initPanel() {
                const { luminosityMaterial, bloomCompositeMaterial, compositeMaterial } = RenderManager;

                const physics = this.physics;

                const vector3 = new Vector3();
                const gravity = new Vector3(0, -9.81, 0);

                const physicsOptions = {
                    Off: false,
                    Physics: true
                };

                const items = [
                    {
                        name: 'FPS'
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'list',
                        list: physicsOptions,
                        value: getKeyByValue(physicsOptions, SceneController.enabled),
                        callback: value => {
                            SceneController.enabled = physicsOptions[value];

                            // Reset
                            vector3.set(0, 0, 0);
                            const array = vector3.toArray();

                            physics.objects.forEach(object => {
                                const { name, position, quaternion } = object;

                                physics.setPosition(name, position.toArray());
                                physics.setOrientation(name, quaternion.toArray());
                                physics.setLinearVelocity(name, array);
                                physics.setAngularVelocity(name, array);
                            });

                            // Flush the last frame
                            physics.update();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Gravity',
                        min: -10,
                        max: 10,
                        step: 0.1,
                        value: -gravity.y,
                        callback: value => {
                            gravity.y = -value;
                            physics.setGravity(gravity.toArray());
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'slider',
                        name: 'Thresh',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uThreshold.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uThreshold.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Smooth',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uSmoothing.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uSmoothing.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Strength',
                        min: 0,
                        max: 2,
                        step: 0.01,
                        value: RenderManager.bloomStrength,
                        callback: value => {
                            RenderManager.bloomStrength = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Radius',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: RenderManager.bloomRadius,
                        callback: value => {
                            RenderManager.bloomRadius = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Chroma',
                        min: 0,
                        max: 10,
                        step: 0.1,
                        value: compositeMaterial.uniforms.uBloomDistortion.value,
                        callback: value => {
                            compositeMaterial.uniforms.uBloomDistortion.value = value;
                        }
                    }
                ];

                items.forEach(data => {
                    this.ui.addPanel(new PanelItem(data));
                });
            }
        }

        const BlurDirectionX = new Vector2(1, 0);
        const BlurDirectionY = new Vector2(0, 1);

        class RenderManager {
            static init(renderer, scene, camera) {
                this.renderer = renderer;
                this.scene = scene;
                this.camera = camera;

                // Unreal bloom
                this.luminosityThreshold = 0.1;
                this.luminositySmoothing = 1;
                this.bloomStrength = 0.3;
                this.bloomRadius = 0.2;
                this.bloomDistortion = 1;

                this.enabled = true;

                this.initRenderer();
            }

            static initRenderer() {
                const { screenTriangle } = WorldController;

                // Fullscreen triangle
                this.screenCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
                this.screen = new Mesh(screenTriangle);
                this.screen.frustumCulled = false;

                // Render targets
                this.renderTarget = new WebGLRenderTarget(1, 1, {
                    depthBuffer: false
                });

                this.renderTargetBright = this.renderTarget.clone();
                this.renderTargetsHorizontal = [];
                this.renderTargetsVertical = [];
                this.nMips = 5;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal.push(this.renderTarget.clone());
                    this.renderTargetsVertical.push(this.renderTarget.clone());
                }

                this.renderTarget.depthBuffer = true;

                // Luminosity high pass material
                this.luminosityMaterial = new LuminosityMaterial();
                this.luminosityMaterial.uniforms.uThreshold.value = this.luminosityThreshold;
                this.luminosityMaterial.uniforms.uSmoothing.value = this.luminositySmoothing;

                // Separable Gaussian blur materials
                this.blurMaterials = [];

                const kernelSizeArray = [3, 5, 7, 9, 11];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.blurMaterials.push(new UnrealBloomBlurMaterial(kernelSizeArray[i]));
                }

                // Unreal bloom composite material
                this.bloomCompositeMaterial = new BloomCompositeMaterial();
                this.bloomCompositeMaterial.uniforms.tBlur1.value = this.renderTargetsVertical[0].texture;
                this.bloomCompositeMaterial.uniforms.tBlur2.value = this.renderTargetsVertical[1].texture;
                this.bloomCompositeMaterial.uniforms.tBlur3.value = this.renderTargetsVertical[2].texture;
                this.bloomCompositeMaterial.uniforms.tBlur4.value = this.renderTargetsVertical[3].texture;
                this.bloomCompositeMaterial.uniforms.tBlur5.value = this.renderTargetsVertical[4].texture;
                this.bloomCompositeMaterial.uniforms.uBloomFactors.value = this.bloomFactors();

                // Composite material
                this.compositeMaterial = new SceneCompositeDistortionMaterial({ dithering: true });
                this.compositeMaterial.uniforms.uBloomDistortion.value = this.bloomDistortion;
            }

            static bloomFactors() {
                const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    const factor = bloomFactors[i];
                    bloomFactors[i] = this.bloomStrength * MathUtils.lerp(factor, 1.2 - factor, this.bloomRadius);
                }

                return bloomFactors;
            }

            // Public methods

            static resize = (width, height, dpr) => {
                this.renderer.setPixelRatio(dpr);
                this.renderer.setSize(width, height);

                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.renderTarget.setSize(width, height);

                // Unreal bloom
                width = Math.round(width / 2);
                height = Math.round(height / 2);

                this.renderTargetBright.setSize(width, height);

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal[i].setSize(width, height);
                    this.renderTargetsVertical[i].setSize(width, height);

                    this.blurMaterials[i].uniforms.uResolution.value.set(width, height);

                    width = Math.round(width / 2);
                    height = Math.round(height / 2);
                }
            };

            static update = () => {
                const renderer = this.renderer;
                const scene = this.scene;
                const camera = this.camera;

                if (!this.enabled) {
                    renderer.setRenderTarget(null);
                    renderer.render(scene, camera);
                    return;
                }

                const renderTarget = this.renderTarget;
                const renderTargetBright = this.renderTargetBright;
                const renderTargetsHorizontal = this.renderTargetsHorizontal;
                const renderTargetsVertical = this.renderTargetsVertical;

                // Scene pass
                renderer.setRenderTarget(renderTarget);
                renderer.render(scene, camera);

                // Extract bright areas
                this.luminosityMaterial.uniforms.tMap.value = renderTarget.texture;
                this.screen.material = this.luminosityMaterial;
                renderer.setRenderTarget(renderTargetBright);
                renderer.render(this.screen, this.screenCamera);

                // Blur all the mips progressively
                let inputRenderTarget = renderTargetBright;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.screen.material = this.blurMaterials[i];

                    this.blurMaterials[i].uniforms.tMap.value = inputRenderTarget.texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionX;
                    renderer.setRenderTarget(renderTargetsHorizontal[i]);
                    renderer.render(this.screen, this.screenCamera);

                    this.blurMaterials[i].uniforms.tMap.value = this.renderTargetsHorizontal[i].texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionY;
                    renderer.setRenderTarget(renderTargetsVertical[i]);
                    renderer.render(this.screen, this.screenCamera);

                    inputRenderTarget = renderTargetsVertical[i];
                }

                // Composite all the mips
                this.screen.material = this.bloomCompositeMaterial;
                renderer.setRenderTarget(renderTargetsHorizontal[0]);
                renderer.render(this.screen, this.screenCamera);

                // Composite pass (render to screen)
                this.compositeMaterial.uniforms.tScene.value = renderTarget.texture;
                this.compositeMaterial.uniforms.tBloom.value = renderTargetsHorizontal[0].texture;
                this.screen.material = this.compositeMaterial;
                renderer.setRenderTarget(null);
                renderer.render(this.screen, this.screenCamera);
            };
        }

        class InputManager {
            static init(scene, camera) {
                this.scene = scene;
                this.camera = camera;

                this.raycaster = new Raycaster();
                this.raycaster.layers.set(layers.picking);

                this.mouse = new Vector2();
                this.hover = null;
                this.selected = null;
                this.isDown = false;
                this.enabled = true;

                this.initMesh();

                this.addListeners();
            }

            static initMesh() {
                const { quad } = WorldController;

                let material;

                if (isDebug) {
                    material = new MeshBasicMaterial({
                        color: 0xff0000,
                        wireframe: true
                    });
                } else {
                    material = new MeshBasicMaterial({ visible: false });
                }

                this.dragPlane = new Mesh(quad, material);
                this.dragPlane.scale.multiplyScalar(200);
                this.dragPlane.layers.enable(layers.picking);
            }

            static addListeners() {
                window.addEventListener('pointerdown', this.onPointerDown);
                window.addEventListener('pointermove', this.onPointerMove);
                window.addEventListener('pointerup', this.onPointerUp);
            }

            // Event handlers

            static onPointerDown = e => {
                if (!this.enabled) {
                    return;
                }

                this.isDown = true;

                this.onPointerMove(e);
            };

            static onPointerMove = ({ clientX, clientY }) => {
                if (!this.enabled) {
                    return;
                }

                this.mouse.x = (clientX / document.documentElement.clientWidth) * 2 - 1;
                this.mouse.y = 1 - (clientY / document.documentElement.clientHeight) * 2;

                if (this.selected) {
                    this.raycaster.setFromCamera(this.mouse, this.camera);

                    const intersection = this.raycaster.intersectObject(this.dragPlane);

                    if (intersection.length) {
                        const point = intersection[0].point;

                        SceneController.physics.setPosition('mouse', point.toArray());
                    }

                    return;
                }

                this.raycaster.setFromCamera(this.mouse, this.camera);

                const intersection = this.raycaster.intersectObjects(this.scene.children);

                if (intersection.length) {
                    let object = intersection[0].object;

                    if (object.parent.isGroup) {
                        object = object.parent;
                    }

                    if (this.isDown && this.selected !== object) {
                        this.selected = object;

                        const point = intersection[0].point;
                        const array = point.toArray();

                        SceneController.physics.setPosition('mouse', array);

                        SceneController.physics.addJoint({
                            name: 'mouseJoint',
                            type: 'joint',
                            mode: 'spherical',
                            body1: object.name,
                            body2: 'mouse',
                            worldAnchor: array,
                            springDamper: [4, 1]
                        });

                        this.dragPlane.position.copy(point);
                        this.dragPlane.quaternion.copy(this.camera.quaternion);

                        this.scene.add(this.dragPlane);

                        CameraController.enabled = false;

                        document.body.style.cursor = 'move';
                    } else if (this.hover !== object) {
                        this.hover = object;
                        document.body.style.cursor = 'pointer';
                    }
                } else if (this.hover) {
                    this.hover = null;
                    document.body.style.cursor = '';
                }
            };

            static onPointerUp = () => {
                if (!this.enabled) {
                    return;
                }

                if (this.selected) {
                    this.scene.remove(this.dragPlane);

                    SceneController.physics.remove('mouseJoint');

                    this.selected = null;

                    CameraController.enabled = true;
                }

                this.isDown = false;
            };
        }

        class CameraController {
            static init(camera) {
                this.camera = camera;

                this.mouse = new Vector2();
                this.lookAt = new Vector3(0, 0, -2);
                this.origin = new Vector3();
                this.target = new Vector3();
                this.targetXY = new Vector2(2, 0.4);
                this.origin.copy(this.camera.position);

                this.lerpSpeed = 0.02;
                this.enabled = false;

                this.addListeners();
            }

            static addListeners() {
                window.addEventListener('pointermove', this.onPointerMove);
            }

            // Event handlers

            static onPointerMove = ({ clientX, clientY }) => {
                if (!this.enabled) {
                    return;
                }

                this.mouse.x = (clientX / document.documentElement.clientWidth) * 2 - 1;
                this.mouse.y = 1 - (clientY / document.documentElement.clientHeight) * 2;
            };

            // Public methods

            static resize = (width, height) => {
                this.camera.aspect = width / height;
                this.camera.updateProjectionMatrix();

                if (width < height) {
                    this.targetXY.x = 1;
                } else {
                    this.targetXY.x = 2;
                }
            };

            static update = () => {
                if (!this.enabled) {
                    return;
                }

                this.target.x = this.origin.x + this.targetXY.x * this.mouse.x;
                this.target.y = this.origin.y + this.targetXY.y * this.mouse.y;
                this.target.z = this.origin.z;

                this.camera.position.lerp(this.target, this.lerpSpeed);
                this.camera.lookAt(this.lookAt);
            };

            static animateIn = () => {
                this.enabled = true;
            };
        }

        class WorldController {
            static init() {
                this.initWorld();
                this.initLights();
                this.initLoaders();
                this.initEnvironment();
                this.initPhysics();

                this.addListeners();
            }

            static initWorld() {
                this.renderer = new WebGLRenderer({
                    powerPreference: 'high-performance',
                    antialias: true
                });

                // Output canvas
                this.element = this.renderer.domElement;

                // Disable color management
                ColorManagement.enabled = false;
                this.renderer.outputColorSpace = LinearSRGBColorSpace;

                // Shadows
                this.renderer.shadowMap.enabled = true;
                this.renderer.shadowMap.type = BasicShadowMap;

                // 3D scene
                this.scene = new Scene();
                this.scene.background = new Color(0x060606);
                this.camera = new PerspectiveCamera(30);
                this.camera.near = 0.5;
                this.camera.far = 40;
                this.camera.position.z = 8;
                this.camera.lookAt(this.scene.position);

                // Global geometries
                this.quad = new PlaneGeometry(1, 1);
                this.screenTriangle = getFullscreenTriangle();

                // Global uniforms
                this.resolution = { value: new Vector2() };
                this.texelSize = { value: new Vector2() };
                this.aspect = { value: 1 };
                this.time = { value: 0 };
                this.frame = { value: 0 };

                // Global settings
                this.anisotropy = this.renderer.capabilities.getMaxAnisotropy();
            }

            static initLights() {
                this.scene.add(new HemisphereLight(0x606060, 0x404040, 3));

                const light = new DirectionalLight(0xffffff, 2);
                light.position.set(5, 5, 5);
                light.castShadow = true;
                light.shadow.mapSize.width = 2048;
                light.shadow.mapSize.height = 2048;
                this.scene.add(light);

                this.light = light;
            }

            static initLoaders() {
                this.textureLoader = new TextureLoader();
                this.textureLoader.setPath('../assets/textures/');

                this.environmentLoader = new EnvironmentTextureLoader(this.renderer);
                this.environmentLoader.setPath('../assets/textures/env/');
            }

            static async initEnvironment() {
                this.scene.environment = await this.loadEnvironmentTexture('jewelry_black_contrast.jpg');
                this.scene.environmentIntensity = 1.2;
            }

            static initPhysics() {
                this.physics = new ScenePhysicsController();
            }

            static addListeners() {
                this.renderer.domElement.addEventListener('touchstart', this.onTouchStart);
            }

            // Event handlers

            static onTouchStart = e => {
                e.preventDefault();
            };

            // Public methods

            static resize = (width, height, dpr) => {
                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.resolution.value.set(width, height);
                this.texelSize.value.set(1 / width, 1 / height);
                this.aspect.value = width / height;
            };

            static update = (time, delta, frame) => {
                this.time.value = time;
                this.frame.value = frame;
            };

            static ready = () => Promise.all([
                this.textureLoader.ready(),
                this.environmentLoader.ready()
            ]);

            // Global handlers

            static getTexture = (path, callback) => this.textureLoader.load(path, callback);

            static loadTexture = path => this.textureLoader.loadAsync(path);

            static loadEnvironmentTexture = path => this.environmentLoader.loadAsync(path);
        }

        class App {
            static async init() {
                this.initThread();
                this.initLoader();
                this.initWorld();
                this.initViews();
                this.initControllers();

                this.addListeners();
                this.onResize();

                await Promise.all([
                    SceneController.ready(),
                    this.loader.ready()
                ]);

                await WorldController.ready();

                this.initAudio();
                this.initPanel();

                CameraController.animateIn();
                SceneController.animateIn();
            }

            static initThread() {
                ImageBitmapLoaderThread.init();

                Thread.count--; // Make room for the physics thread
            }

            static initLoader() {
                this.loader = new BufferLoader();
                this.loader.setPath('../assets/sounds/');
                this.loader.loadAll(['gong.mp3']);
            }

            static initWorld() {
                WorldController.init();
                document.body.appendChild(WorldController.element);
            }

            static initViews() {
                this.view = new SceneView();
                WorldController.scene.add(this.view);

                this.ui = new UI({ fps: true });
                this.ui.animateIn();
                document.body.appendChild(this.ui.element);
            }

            static initControllers() {
                const { renderer, scene, camera, physics } = WorldController;

                CameraController.init(camera);
                SceneController.init(physics, this.view);
                InputManager.init(scene, camera);
                RenderManager.init(renderer, scene, camera);
            }

            static initAudio() {
                const { scene, camera } = WorldController;

                WebAudio.init({ sampleRate: 48000 });
                WebAudio.load(this.loader.files);

                AudioController.init(scene, camera, this.view);
            }

            static initPanel() {
                const { physics } = WorldController;

                PanelController.init(physics, this.ui);
            }

            static addListeners() {
                window.addEventListener('resize', this.onResize);
                ticker.add(this.onUpdate);
                ticker.start();
            }

            // Event handlers

            static onResize = () => {
                const width = document.documentElement.clientWidth;
                const height = document.documentElement.clientHeight;
                const dpr = window.devicePixelRatio;

                WorldController.resize(width, height, dpr);
                CameraController.resize(width, height);
                SceneController.resize(width, height);
                RenderManager.resize(width, height, dpr);
            };

            static onUpdate = (time, delta, frame) => {
                WorldController.update(time, delta, frame);
                CameraController.update();
                SceneController.update();
                RenderManager.update(time, delta, frame);
                this.ui.update();
            };
        }

        App.init();
    </script>
</head>
<body>
</body>
</html>
